from django.conf import settings
from django.db import transaction
from django.shortcuts import render, redirect

# Create your views here.
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView


class AvatarView(APIView):
    def post(self, request):
        # 创建FastDFS连接对象
        client = Fdfs_client('shicifang/utils/fastdfs/client.conf')
        # 获取前端传递的image文件,read()读取二进制图片流
        image_data = request.FILES.get('img').read()
        with transaction.atomic():
            # 创建保存点
            save_id = transaction.savepoint()
            # 上传图片到fastDFSexit
            res = client.upload_by_buffer(image_data)
            # 判断是否上传成功
            if res['Status'] != 'Upload successed.':
                # 回滚到保存点
                transaction.savepoint_rollback(save_id)
                return Response(status=status.HTTP_403_FORBIDDEN)
            # 获取上传后的路径
            file_id = res.get('Remote file_id')
            image_url = settings.FDFS_URL + file_id
            # 提交从保存点到当前状态的所有数据库事务操作
            transaction.savepoint_commit(save_id)
        return Response({'imgurl': image_url})


class CommonView(APIView):
    def post(self,request):
        # 创建FastDFS连接对象
        client = Fdfs_client('shicifang/utils/fastdfs/client.conf')
        # 获取前端传递的image文件,read()读取二进制图片流
        image_data = request.FILES.get('upload').read()
        with transaction.atomic():
            # 创建保存点
            save_id = transaction.savepoint()
            # 上传图片到fastDFSexit
            res = client.upload_by_buffer(image_data)
            # 判断是否上传成功
            if res['Status'] != 'Upload successed.':
                # 回滚到保存点
                transaction.savepoint_rollback(save_id)
                return Response(status=status.HTTP_403_FORBIDDEN)
            # 获取上传后的路径
            file_id = res.get('Remote file_id')
            image_url = settings.FDFS_URL + file_id
            # 提交从保存点到当前状态的所有数据库事务操作
            transaction.savepoint_commit(save_id)
        redirect_url = settings.FDFS_REDIRECT_URL + image_url + '&CKEditorFuncNum=1'
        return redirect(redirect_url)